﻿using Microsoft.VisualBasic.FileIO;
using MySql.Data.MySqlClient;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ZC.DBUtils;

namespace AoYing_DeviceCollection
{
    /// <summary>
    /// 公共方法
    /// </summary>
    public static class CommonHelper
    {
        public static Dictionary<string, string> cmdParmDic = new Dictionary<string, string>();
        static string sqlConn = ConfigurationManager.AppSettings["connStr"];
        public static int cmdParmIndex = -1;

  

        public static List<string> GetShareFiled(string path, string fileType)
        {
            List<string> files = Directory.GetFiles(path, fileType)
                               //     .OrderByDescending(file => File.GetCreationTime(file))

                                    .Select(file => Path.GetFileName(file))
                                  // .Take(100) // 取前 100 条
                                    .ToList();

            return files;
        }
        public static string GetResult(string value)
        {
            if (value == "GOOD" || value == "USEROK")
            {
                return "1";
            }
            else
            {
                return "0";
            }
        }
        /// <summary>
        /// 获取路径文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileType"></param>
        /// <returns></returns>
        public static FileInfo[] GetExcelDicList(string path, string fileType)
        {
            DirectoryInfo root = new DirectoryInfo(path);

            return root.GetFiles(fileType);
        }
        /// <summary>
        /// 取文件夹下最新的文件
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public static string GetEarliestFileName(string path, string fileType)
        {
            string[] files = Directory.GetFiles(path, fileType);
            string earliestFile = files.OrderBy(file => File.GetCreationTime(file)).FirstOrDefault();

            if (earliestFile == null)
            {
                return string.Empty;
            }
            return Path.GetFileName(earliestFile);
        }
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="targetFile"></param>
        /// <param name="filesNameTime"></param>
        public static void MoveFile( string targetFile, List<string> filesNameTime)
        {
           
            if (Directory.Exists(targetFile) == false)
            {
                Directory.CreateDirectory(targetFile);
            }
            foreach (var fileName in filesNameTime)
            {
                try
                {
                    // 检查要转移的文件是否存在，不存在则跳过
                    if (!File.Exists(fileName))
                    {
                        continue;
                    }
                    string value = fileName.Substring(fileName.LastIndexOf('\\') + 1);
                    File.Move(fileName, targetFile+"\\"+ value);
                }
                catch (Exception ex)
                {

                    BaseUtils._eventMsg.ErrorMsg = $"【文件转移出错】【{fileName}】{ex.Message}";
                }
              
            }

        }
        public static void MoveFileStr(string sourceFile, string targetFile, string filesNameTime)
        {
            // 确保源文件夹存在
            if (!Directory.Exists(sourceFile))
            {
             //   Console.WriteLine($"源文件夹不存在，正在创建: {sourceFile}");
                Directory.CreateDirectory(sourceFile);
            }

            string sourceFilePath = Path.Combine(sourceFile, filesNameTime);
            string targetFilePath = Path.Combine(targetFile, filesNameTime);

            // 确保目标文件夹存在
            if (!Directory.Exists(targetFile))
            {
              //  Console.WriteLine($"目标文件夹不存在，正在创建: {targetFile}");
                Directory.CreateDirectory(targetFile);
            }

            // 检查目标文件是否存在
            if (File.Exists(targetFilePath))
            {
                // 删除已存在的目标文件
             //   Console.WriteLine($"目标文件已存在，正在删除: {targetFilePath}");
                File.Delete(targetFilePath);
            }

            // 移动文件
          //  Console.WriteLine($"正在移动文件: {sourceFilePath} 到 {targetFilePath}");
            File.Move(sourceFilePath, targetFilePath);
        }
        public static void CopyFiles(string sourceDirectory, string destinationDirectory)
        {
           

            // 确保目标目录存在，如果不存在则创建它
            if (!Directory.Exists(destinationDirectory))
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            // 获取源目录中的所有文件
            string[] files = Directory.GetFiles(sourceDirectory);

            // 遍历文件并复制到目标目录
            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file);
                string destinationPath = Path.Combine(destinationDirectory, fileName);

                File.Copy(file, destinationPath);
            }

        }
    
    /// <summary>
    /// 创建目录
    /// </summary>
    /// <param name="dic"></param>
    public static void CreateDirectory(string dic)
        {
            if (!Directory.Exists(dic))
            {
                Directory.CreateDirectory(dic);
            }
        }
        /// <summary>
        /// 转移文件夹
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="targetFile"></param>
        //public static void MoveFolder(string sourceFile, string targetFile)
        //{
        //    if (!Directory.Exists(sourceFile))
        //    {
        //        Directory.CreateDirectory(sourceFile); 
        //    }

        //    if (!Directory.Exists(targetFile))
        //    {
        //        Directory.CreateDirectory(targetFile);
        //    }

        //    string[] files = Directory.GetFiles(sourceFile); //获取源文件夹中的所有文件

        //    foreach (string file in files)
        //    {
        //        string fileName = Path.GetFileName(file); //获取文件名
        //        string destinationFile = Path.Combine(targetFile, fileName); //生成目标文件的完整路径
        //        File.Move(file, destinationFile); //移动文件
        //    }

        //    Directory.Delete(sourceFile);

        //} 
        /// <summary>
            /// 转移文件夹
            /// </summary>
            /// <param name="sourceFile"></param>
            /// <param name="targetFile"></param>
        public static void MoveFolder(string sourceFile, string targetFile)
        {
            // 检查源文件夹是否存在
            if (!Directory.Exists(sourceFile))
            {
                Console.WriteLine($"源文件夹不存在: {sourceFile}");
                return; // 结束方法
            }

            // 检查目标文件夹是否存在，如果不存在则创建
            if (!Directory.Exists(targetFile))
            {
                Directory.CreateDirectory(targetFile);
            }

            // 获取源文件夹中的所有文件
            string[] files = Directory.GetFiles(sourceFile);

            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file); // 获取文件名
                string destinationFile = Path.Combine(targetFile, fileName); // 生成目标文件的完整路径

                // 如果目标文件已存在，则删除它
                if (File.Exists(destinationFile))
                {
                    File.Delete(destinationFile);
                }

                // 移动文件到目标文件夹
                File.Move(file, destinationFile);
            }

            // 删除源文件夹
            Directory.Delete(sourceFile);
        }

        /// <summary>
        /// Csv文件转datatable
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="colkeyvalue"></param>
        /// <returns></returns>
        public static DataTable CsvToDataTable(string fileName)
        {
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.Default);
            // StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("GBK"));
            string strLine;   //记录每次读取的一行记录
            string[] aryLine;  //记录每行记录中的各字段内容
            int columnCount; //标示列数      
            bool IsFirst = false;    //标示是否是读取的第一行
            bool IsTotalResult = false;
            bool Col = true;
            try
            {  //逐行读取CSV中的数据
                while ((strLine = sr.ReadLine()) != null)
                {
                    if (strLine == "" || strLine.Replace(",", "") == string.Empty)
                    {
                        continue;
                    }
                    aryLine = strLine.Replace(" ", "").Split(',');
                    if (IsFirst == true)
                    {
                        IsFirst = false;
                        columnCount = aryLine.Length;
                        //创建列
                        for (int i = 0; i < columnCount; i++)
                        {
                            DataColumn dc = new DataColumn(i.ToString());
                            dt.Columns.Add(dc);
                        }
                    }
                    else
                    {
                        columnCount = aryLine.Length;
                        if (Col)
                        {

                            //创建列
                            for (int i = 0; i < 30; i++)
                            {
                                if (IsTotalResult == false) { }
                                DataColumn dc = new DataColumn(i.ToString());
                                dt.Columns.Add(dc);
                            }
                            Col = false;
                        }

                        DataRow dr = dt.NewRow();

                        for (int j = 0; j < columnCount; j++)
                        {
                            if (aryLine.Count() > j)
                            {
                                string colvalue = aryLine[j].Trim().Replace("\"","");
                                dr[j] = colvalue;
                            }

                        }
                        dt.Rows.Add(dr);
                    }

                }
            }
            catch (Exception)
            {
                throw;
            }
            sr.Close();
            fs.Close();

            // dt.Rows.Remove(dt.Rows[0]);
            return dt;
        }
        public static DataTable NewCsvToDataTable(string filePath)
        {
            DataTable dt = new DataTable();
            using (TextFieldParser parser = new TextFieldParser(filePath))
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                parser.HasFieldsEnclosedInQuotes = true; // 处理带引号的字段

                // 读取第一行数据（不作为列名）
                string[] firstRow = parser.ReadFields();

                // 根据第一行的列数创建匿名列名（如Column1, Column2...）
                for (int i = 0; i < 60; i++)
                {
                    dt.Columns.Add($"Column{i + 1}"); // 列名格式为Column1, Column2等
                }

                // 将第一行数据添加到DataTable
                dt.Rows.Add(firstRow);

                // 继续读取剩余数据行
                while (!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();
                    dt.Rows.Add(fields);
                }
            }
            return dt;
        }
        public static string GetKeys(string value)
        {
            if (cmdParmDic.ContainsValue(value))
            {
                return cmdParmDic.FirstOrDefault(q => q.Value == value).Key;
            }

            cmdParmIndex++;
            cmdParmDic.Add($"@keys{cmdParmIndex}", value);
            return $"@keys{cmdParmIndex}";

        }
        public static void ExeSql(StringBuilder sql)
        {
            CmdParameter[] parameters = null;
            parameters = InitParam(parameters);
            if (!new BaseSQL(sqlConn).ExeSql(sql.ToString(), parameters))
            {
                BaseUtils._eventMsg.ErrorMsg = $"【sql执行失败】";
               // throw new Exception($"执行失败");
            }
        }
        public static DataTable GetDataTable(StringBuilder sql)
        {
            CmdParameter[] parameters = null;
            parameters = InitParam(parameters);
            return new BaseSQL(sqlConn).QueryDt(sql.ToString(), parameters);
        }
        public static DataTable GetDataTable(string sql)
        {
            CmdParameter[] parameters = null;
            parameters = InitParam(parameters);
            return new BaseSQL(sqlConn).QueryDt(sql.ToString(), parameters);
        }
        public static DataSet GetDataSet(string sql)
        {
            CmdParameter[] parameters = null;
            parameters = InitParam(parameters);
            return new BaseSQL(sqlConn).QuserDs(sql.ToString(), parameters);
        }
        public static CmdParameter[] InitParam(CmdParameter[] parameters)
        {
            parameters = new CmdParameter[cmdParmDic.Count];
            int index = 0;
            foreach (var item in cmdParmDic)
            {
                parameters[index] = new CmdParameter() { DBtype = DBType.String, ParameterName = item.Key, Value = item.Value };
                index++;
            }
            return parameters;
        }
        public static string GetInsertSQL(object entity, string tableName)
        {
            Type t = entity.GetType();
            PropertyInfo[] propertyInfo = t.GetProperties();

            if (propertyInfo.Count() > 1)
            {
                var sql = "insert into " + tableName;  //定义好类名即数据表名
                var fieldList = string.Empty;
                var fieldVals = string.Empty;
                foreach (var field in propertyInfo)
                {
                    if (field.Name.CompareTo("Id") == 0)
                    {
                        continue;
                    }
                    switch (field.PropertyType.Name)
                    {
                        case "String":
                            fieldList += field.Name + ",";
                            fieldVals += $"'{field.GetValue(entity, null)}',";
                            break;
                        case "Int32":
                            fieldList += field.Name + ",";
                            fieldVals += field.GetValue(entity, null) + ",";
                            break;
                        case "Double":
                            fieldList += field.Name + ",";
                            fieldVals += field.GetValue(entity, null) + ",";
                            break;
                        case "Boolean":
                            fieldList += field.Name + ",";
                            fieldVals += ((bool)field.GetValue(entity, null) ? 1 : 0) + ",";
                            break;
                        case "DateTime":
                            fieldList += field.Name + ",";
                            fieldVals += $"'{field.GetValue(entity, null)}',";
                            break;
                        default:
                            break;
                    }
                }
                fieldList = fieldList.Remove(fieldList.Length - 1);
                fieldVals = fieldVals.Remove(fieldVals.Length - 1);
                sql += "(" + fieldList + ")" + "values" + "(" + fieldVals + ");";
                return sql;
            }

            return string.Empty;
        }
        public static FileInfo CopyFileToExpirePath(FileInfo file, string expirePath)
        {
            // 确保目标文件夹存在，如果不存在则创建
            if (!Directory.Exists(expirePath))
            {
                Directory.CreateDirectory(expirePath);
            }

            // 获取目标文件的完整路径
            string destinationFilePath = Path.Combine(expirePath, file.Name);

            // 复制文件到目标路径，若文件已存在则覆盖
            File.Copy(file.FullName, destinationFilePath, true);

            // 返回目标路径下的新文件 FileInfo
            return new FileInfo(destinationFilePath);
        }
        /// <summary>
        /// 修改文件名
        /// </summary>
        /// <param name="filepath"></param>
        public static string RenameFile(string filepath)
        {
            //获取时间戳相差到秒
            string currentTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            // 获取文件名（包括扩展名）
            string newFileName = Path.GetFileNameWithoutExtension(filepath) + "_" + currentTime + Path.GetExtension(filepath);
            // 将原文件名和新后缀拼接起来生成新的文件名
            string newfilepath = Path.Combine(Path.GetDirectoryName(filepath), newFileName);
            // 将新文件名与文件所在路径拼接起来生成新文件的完整路径
            File.Move(filepath, newfilepath); // 修改文件名

            return newfilepath;
        }

        /// <summary>
        /// 转移文件
        /// </summary>
        /// <param name="movePath"></param>
        /// <param name="file"></param>
        public static void TransFile(string movePath, FileInfo file)
        {
            if (File.Exists(movePath))
            {
                FileInfo deleteFile = new FileInfo(movePath);
                File.SetAttributes(deleteFile.FullName, FileAttributes.Normal);
                File.Delete(deleteFile.FullName);
                deleteFile.Delete();
            }

            if (File.Exists(file.FullName))
            {
                file.MoveTo(movePath); //转移文件
            }
        }
        /// <summary>
        /// 测试IP
        /// </summary>
        /// <param name="ServerIP"></param>
        /// <returns></returns>

        public static bool IsServerConnected(string path)
        {
            Ping pingSender = new Ping();

            Regex reg = new Regex(@"((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)");

            Match match = reg.Match(path);

            string ipvalue = match.Value;

            PingReply reply = null;
            //先判断是不是共享路径,如果是Ping一下，看下网络状态。
            if (ipvalue != null && ipvalue != "")
            {
                //是共享路径
                reply = pingSender.Send(ipvalue, 500);
                if (reply.Status != IPStatus.Success)
                {
                    return false;
                }
            }
            return true;
        }
        public static bool IsToday(string dateTimeString)
        {
            DateTime dateTime = DateTime.Parse(dateTimeString);
            DateTime today = DateTime.Today;

            return dateTime.Date == today;
        }
        /// <summary>
        /// Http Post
        /// </summary>
        /// <param name="uri">资源地址</param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static string HttpPost(string uri, string body)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            if (!string.IsNullOrEmpty(body))
            {
                byte[] buffer = encoding.GetBytes(body);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
            }
            else
            {
                request.ContentLength = 0;
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

    }
}
